package com.qfedu.interceptor;

import com.qfedu.anno.LoginAnno;
import com.qfedu.entity.CustomerEntity;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginCheck implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //该拦截器至拦截指定注解的方法
        //判断请求方法是否包含该注解
        if (handler instanceof HandlerMethod){
            HandlerMethod hm = (HandlerMethod) handler;
            if (hm.hasMethodAnnotation(LoginAnno.class)){
                CustomerEntity customerinfo = (CustomerEntity)request.getSession().getAttribute("customerinfo");
                if (customerinfo==null || "".equals(customerinfo)){
                    response.sendRedirect("login.jsp");
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
